#import "mgr_game_physics.h"

#define SCRREN_IN_METER 5 /*屏幕最长对应的box2d单位长度*/

CMgrGamePhysics *CMgrGamePhysics::instance;

void CMgrGamePhysics::InitInstance(void)
{
	if (NULL == instance)
	{
		instance = new CMgrGamePhysics;
	}
}

void CMgrGamePhysics::FreeInstance(void)
{
	if (NULL != instance)
	{
		delete instance;
		instance = NULL;
	}
}

CMgrGamePhysics *CMgrGamePhysics::Instance(void)
{
	return instance;
}

b2World *CMgrGamePhysics::World(void)
{
	return instance->world;
}

float CMgrGamePhysics::Ratio(void)
{
	return instance->ratio;
}

void CMgrGamePhysics::Update(void)
{
	if (NULL != world)
	{
		world->Step(1.0 / 60.0, 10, 10);
	}
}

void CMgrGamePhysics::BeginContact(b2Contact *Contact)
{
	[g_LayerGameObject BeginContact:Contact];
}

void CMgrGamePhysics::EndContact(b2Contact *Contact)
{
	[g_LayerGameObject EndContact:Contact];
}

b2Vec2 CMgrGamePhysics::GetBodyPos(b2Body *Body)
{
	b2Vec2 _Ret;

	assert(NULL != Body);
	_Ret = Body->GetPosition();
	_Ret.x *= ratio;
	_Ret.y *= ratio;
	return _Ret;
}

float CMgrGamePhysics::GetBodyAngle(b2Body *Body)
{
	return -1 * CC_RADIANS_TO_DEGREES(Body->GetAngle());
}

CMgrGamePhysics::CMgrGamePhysics(void)
{
	world = new b2World(b2Vec2(0.0f, 0.0f), false);
	world->SetContactListener(this);

	ratio = g_ScrrenSize.width > g_ScrrenSize.height ? g_ScrrenSize.width / SCRREN_IN_METER : g_ScrrenSize.height / SCRREN_IN_METER;
}

CMgrGamePhysics::~CMgrGamePhysics(void)
{
	if (NULL != world)
	{
		delete world;
		world = NULL;
	}
}